import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbteacherlist, tbtheteacherisqualifiedforthecurriculum } from '../../../atoms/db';
import getuser from '../../../atoms/getuser';

const logger = anylogger('pages/api/teacher/query.api');

export type IData = ITbteacherlist;

export type Result = {
	count: number;
	data: IData[];
};

export type Query = {
	q: string;
	page: string;
	pagesize: string;
}


/**
 * 查询服务
 */
const handler = an48<Result>();

handler.get(async (req, res) => {
	try {
		logger.debug('msg query:', req.query);
		const { q, ...rest } = req.query as Query;
		const page = Number(rest.page || '1');
		const pagesize = Number(rest.pagesize || '10');
		const user = await getuser(req);
		// false '' undefined null 0
		if (!user || user.role !== 'admin') {
			res.status(200).json({
				count: 0,
				data: []
			});
			return;
		}
		const dt1 = tbteacherlist();
		if (q) {
			const query = q.trim();
			dt1.where('teachername', 'like', `%${query}%`);
		}
		const [{ size }] = await tbteacherlist().count('*', { as: 'size' });
		const count = Number(size);
		const dt2 = tbteacherlist();
		if (q && typeof q === 'string') {
			const query = q.trim();
			dt2.where('teachername', 'like', `%${query}%`);
		}
		const offset = (page - 1) * pagesize;
		const d = await dt2
			.select('*')
			.limit(pagesize)
			.offset(offset)
			.orderBy('teachername', 'asc')
			.orderBy('teacher_id', 'asc');
		// todo 以下查询教师课程的逻辑不对
		// const datateachers = await tbtheteacherisqualifiedforthecurriculum().select('*');
		// const mapteachers = datateachers.reduce((pre, cur) => {
		// 	return pre.set(cur.curriculum_id, cur.coursename);
		// }, new Map<string, string>());

		const data = d.map((it) => {
			// const coursename = mapteachers.get(it.teacher_id);
			return {
				...it
			} as IData;
		});

		res.status(200).json({
			count, data
		});
	} catch (error) {
		logger.trace(error);
		res.status(200).json({
			count: 0,
			data: []
		});
	}
});

export const config = {} as PageConfig;

export default handler;
